package capitulo9;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Exercises extends JFrame implements KeyListener{
	SoundClip[] sounds = new SoundClip[4];
	int soundSelected = 0;
	String nameSound = "";
	
	MidiSequence[] musics = new MidiSequence[3];
	int musicSelected = 0;
	String nameMusic = "";
		
	public static void main(String[] args) {
		new Exercises();
	}

	public Exercises(){
		super("Exercises Chapter 9");
		setSize(500,400);
		this.setLocationRelativeTo(this);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// Load all the sounds
		sounds[0] = new SoundClip("explode.wav");
		sounds[1] = new SoundClip("gong.wav");
		sounds[2] = new SoundClip("shoot.wav");
		sounds[3] = new SoundClip("thrust.wav");

		musics[0] = new MidiSequence("battlestargalactica.mid");
		musics[1] = new MidiSequence("bsg.mid");
		musics[2] = new MidiSequence("titlemusic.mid");
				
		// Enable the Keylistener
		addKeyListener(this);
	}
	
	public void paint(Graphics g){
		g.setColor(Color.WHITE);
		g.fillRect(0,0,500,400);
		g.setColor(Color.BLACK);
		g.drawString(nameSound, 10, 40);
		g.drawString(nameMusic, 10, 55);
	}
	
	
	@Override
	public void keyPressed(KeyEvent e) {
		soundSelected = 0;
		nameSound = "";
		
		musicSelected = 0;
		nameMusic = "";
		
		if (e.getKeyCode() > 48 && e.getKeyCode() < 53){
			soundSelected = e.getKeyCode()-49;
			sounds[soundSelected].play();
			nameSound = sounds[soundSelected].getFilename();
		}
		
		switch(e.getKeyCode()){
		case KeyEvent.VK_A:
			muteAllMusic();
			musicSelected = 0;
			musics[musicSelected].play();
			nameMusic = musics[musicSelected].getFilename();
			break;
		case KeyEvent.VK_B:
			muteAllMusic();
			musicSelected = 1;
			musics[musicSelected].play();
			nameMusic = musics[musicSelected].getFilename();
			break;
		case KeyEvent.VK_C:
			muteAllMusic();
			musicSelected = 2;
			musics[musicSelected].play();
			nameMusic = musics[musicSelected].getFilename();
			break;
		}
		
		repaint();
	}

	@Override
	public void keyReleased(KeyEvent e) { }

	@Override
	public void keyTyped(KeyEvent e) { }

	public void muteAllMusic(){	
		for (MidiSequence seq:musics){
			if (seq.getIsPlaying()) 
				seq.stop();
		}
	}
}
